#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#Kiwi Bot
#Make by @nge1nCorsic4 in 2010
#Modified by @nge1nCorsic4 in 2011


#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import kiwi, kiwi.plugin, kiwi.events, kiwi.config, kiwi.lang, threading, random, time

class pub(kiwi.plugin.Plugin):
	def onStart(self):
		ServNumber = kiwi.config.configuration().kiwi.kiwidir
		self.config = kiwi.config.configuration('@kiwi/conf/'+ServNumber+'/pub.cfg')
		self.bdPub = kiwi.bd.bd_pub()
		self.infos = self.config.settings.infos
		self.register = self.main.getPlugin('admin').mod.registerCommand
		self.register('note', int(self.config.level.note), self._note, "Ecrire un message FUN au serveur.")
		self.register('news', int(self.config.level.news), self._news, "Verifie les nouveaux messages du serveur.")
		self.register('infos', int(self.config.level.infos), self._infos, "Affiche les serveurs -]fun[-.")
		self.register('time', int(self.config.level.time), self._time, "Affiche l'heure.")
		self.registerEvent(kiwi.events.EVT_CLIENT_SAY,self.getMessage)
		self.waiting = False
		self.message = None
		self.start = True
		self.pub()
	def onStop(self):
		self.main.getPlugin('admin').mod.deleteCommand('note')
		self.main.getPlugin('admin').mod.deleteCommand('rmnote')
		self.main.getPlugin('admin').mod.deleteCommand('infos')
		self.main.getPlugin('admin').mod.deleteCommand('time')
		self.start = False
	def pub(self):
		if self.start:
			notes = kiwi.bd.bd_pub().checkNotes()
			# for a in notes:
				# print a
			if notes:
				vals = random.choice(notes)
				if vals[1] == 'date' :
					self.output.say('^4Il est actuellement : ^2%s ^4.'%time.strftime('%Hh%M',time.localtime()))
				elif vals[0] == '0':
					self.output.say(vals[1])
				else:
					name = self.bdPub.checkName(vals[0])[0][0]
					self.output.say('Le %s ^2%s^4: %s'%(vals[2],name,vals[1]))
					self.note = vals
			threading.Timer(170.0, self.pub).start()
	def affiche(self, id, note):
		self.output.tell(id,'^4Une nouvelle Note a ete trouvee :')
		self.output.tell(id,'^7%s'%note[0][0])
		self.getResponse(note)
	def getResponse(self, note):
		if self.message :
			if self.message != 3:
				kiwi.bd.bd_pub().updateNote(note[0][0], self.message)
			note.remove(note[0])
			self.message = None
			if note :
				self.affiche(self.waiting, note)
			else:
				self.waiting = False
		else:
			self.output.tell(self.waiting,'^4Conserver ? ^1o^2(^7oui^2) ^4| ^1n^2(^7non^2) ^4| ^1a^2(^7apres^2)')
			threading.Timer(4.0, self.getResponse,[note]).start()
	def getMessage(self, event):
		if self.waiting:
			if event.id == self.waiting :
				message = event.message
				if len(message) == 1:
					if message == 'o':
						self.message = 1
						self.output.tell(event.id,'^4La Note a ete ajoutee.')
					elif message == 'n':
						self.message = 2
						self.output.tell(event.id,'^4La Note a ete retiree.')
					elif message == 'a':
						self.message = 3
						self.output.tell(event.id,'^4La Note sera traitee plus tard.')
	def _note(self,event):
		if len(event.arguments) > 0:
			note = ' '.join(event.arguments)
			# print len(note)
			if len(note) <= 50:
				guid = self.clients.getClientById(event.id)[0].guid
				date = time.strftime('%d-%m-%y',time.localtime())
				self.output.tell(event.id,'^4La Note a ete prise en compte.')
				self.bdPub.insertNote(guid, note, date)
			else:
				self.output.tell(event.id, "Message trop long.(50 carateres max)")
		else:
			self.output.tell(event.id, "Aucun Arguments.")
	def _news(self,event):
		if self.waiting == False :
			newNotes = kiwi.bd.bd_pub().checkNewNotes()
			if newNotes :
				self.waiting = event.id
				self.affiche(self.waiting, newNotes)
			else:
				self.output.tell(event.id,"^7Aucune nouvelle note trouvee...")
	def _rmnote(self, event):
		if self.note :
			kiwi.bd.bd_pub().updateNote(self.note[1], 2)
			self.output.tell(event.id,'^4La Note :^5 %s ^4a ete retiree.'%self.note[1])
	def _infos(self, event):
		for a in self.infos.split(","):
			self.output.tell(event.id,a)
	def _time(self, event):
		self.output.tell(event.id,'^4Il est actuellement : ^2%s ^4.'%time.strftime('%Hh%M',time.localtime()))
			
